system関数は、OS提供のコマンドを実行します。なお、この関数はコマンドが終了するまで待ち状態になります。
#include <stdlib.h>
int system(const char *command);
*commandは実行するコマンドを指定します。
戻り値として、コマンドの終了ステータスを返します。また、コマンドが実行できなかった場合は-1を返します。
次の例題プログラムは、「cat -n ファイルパス名」形式のコマンドを実行しています。
プログラム 例
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char command[50] = 'cat -n ';
if (argc == 2) {
/* catコマンドを生成 */
strcat(command, argv[1]);
/* コマンド実行 */
if (system(command) == -1) {
printf('コマンドが実行できませんでした\n');
}
}
else {
printf('実行時引数の数が不当です\n');
}
return 0;
}
例の実行結果
$ ./system.exe temp.txt
1 #include <stdio.h>
2
3 int main()
4 {
5 printf('Hello World!!.\n');
6
7 return 0;
8 }
$
$ ./system.exe temp_01.txt
cat: temp_01.txt: そのようなファイルやディレクトリはありません
$